// 图标
chrome.runtime.onInstalled.addListener(({ reason }) => {
    chrome.action.setBadgeText({
        text: 'OFF',
    });
    if (reason === 'install') {
        chrome.storage.local.set({
            apiSuggestions: ['tabs', 'storage', 'scripting'],
        });
    }
});

// 点击action
chrome.action.onClicked.addListener(async (tab) => {
    chrome.storage.local.get('signed_in', (data) => {
        if (data.signed_in) {
            // chrome.action.setPopup({ popup: 'popup/popup.html' });
        } else {
            // chrome.action.setPopup({ popup: 'popup/popup.html' });
        }
    });

    if (tab.url.startsWith('http')) {
        // Retrieve the action badge to check if the extension is 'ON' or 'OFF'
        const prevState = await chrome.action.getBadgeText({ tabId: tab.id });
        // Next state will always be the opposite
        const nextState = prevState === 'ON' ? 'OFF' : 'ON';

        // Set the action badge to the next state
        await chrome.action.setBadgeText({
            tabId: tab.id,
            text: nextState,
        });

        if (nextState === 'ON') {
            // Insert the CSS file when the user turns the extension on
            await chrome.scripting.insertCSS({
                files: ['rules.css'],
                target: { tabId: tab.id },
            });
        } else if (nextState === 'OFF') {
            // Remove the CSS file when the user turns the extension off
            await chrome.scripting.removeCSS({
                files: ['rules.css'],
                target: { tabId: tab.id },
            });
        }
    }

    // 你要注入的 JavaScript 代码，作为字符串
    const scriptString = `
  document.body.style.backgroundColor = 'lightgreen';
  console.log('脚本注入成功!');
`;
    const foundTabs = await chrome.tabs.query({});
    const bgTab = foundTabs.find((tab) => tab.url === chrome.runtime.getURL('background.html'));

    console.log(bgTab, 'bgTab');
    if (bgTab) {
        // 使用 chrome.scripting.executeScript 注入脚本
        chrome.scripting.executeScript({
            target: { tabId: bgTab.id }, // 目标标签页
            func: (scriptString) => {
                try {
                    // const func = new Function(scriptString);
                    // console.log(scriptString, func.toString());
                    eval(scriptString);
                } catch (error) {
                    console.error(error);
                }
            }, // 将字符串转换为函数执行
            args: [scriptString],
        });
    }
});
